//************************************************************************
//Developed by Guo Ming Li 2009/2010
//Source code:
//  The source code may be freely modified or used but this credit section may not be removed 
//  The original author must be notified of any modifications plus a copy of 
//  the changed source code
//Contact info: mailto://gming.li@gmail.com
//************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.ExplorerOM;

namespace GML.BizTalk.OperationManager.Library
{
    public class Parties
    {
        public static void RemoveParties(string btsDbServerName, string btsMgntDbName, string sPartyName)
        {
            BtsCatalogExplorer root = new BtsCatalogExplorer();
            List<Party> parties = new List<Party>();

            try
            {
                root.ConnectionString = Helper.GetConnectionString(btsDbServerName, btsMgntDbName);

                foreach (Party party in root.Parties)
                {
                    parties.Add(party);
                }
                //Remove a receive port.
                foreach (Party party in parties)
                {
                    if(string.IsNullOrEmpty(sPartyName) || party.Name.Equals(sPartyName)){
                        root.RemoveParty(party);
                    }
                }

                //Try to commit the changes made so far. 
                root.SaveChanges();
            }
            catch (Exception e)//If it fails, roll-back everything we have done so far
            {
                System.Diagnostics.Debug.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
                Logger.doLog(Guid.NewGuid().ToString(), e.Message, Logger.ServerityLevel.ERROR);
                Logger.doLog(Guid.NewGuid().ToString(), e.StackTrace, Logger.ServerityLevel.ERROR);
                root.DiscardChanges();
                throw e;
            }
            finally
            {
                if (root != null) root.Dispose();
                root = null;
                parties = null;
            }
        }
    }
}
